function createTree(arr) {
  const nodeList = [];
  for(let i = 0; i < arr.length; i++) {
    let node;
    if(!arr[i]) {
      node = null;
    } else {
      node = new Node(arr[i])
    }
    nodeList.push(node);
  }
  for(let i = 0; i < nodeList.length; i++) {
    if(2 * i + 1 < nodeList.length) {
      nodeList[i].left = nodeList[2 * i + 1];
    }
    if(2 * i + 2 < nodeList.length) {
      nodeList[i].right = nodeList[2 * i + 2];
    }
  }
  return nodeList[0];
}
function Node(val, left, right, next) {
  this.val = val;
  this.left = left ? left : null;
  this.right = right ? right : null;
  this.next = next ? next : null;
}
/**
 * @param {Node} root
 * @return {Node}
 */
var connect = function(root) {
  if(!root || (!root.left && !root.right)) return root;
  const stack = [], nodeList = [{
    node: root,
    depth: 0
  }];
  while(nodeList.length) {
    const obj = nodeList.shift();
    stack.push(obj);
    const { node, depth } = obj;
    if(node.left) {
      nodeList.push({
        node: node.left,
        depth: depth + 1
      });
    }
    if(node.right) {
      nodeList.push({
        node: node.right,
        depth: depth + 1
      });
    }
  }
  for(let i = 0; i < stack.length - 1; i++) {
    const { node, depth } = stack[i];
    const { node: nextNode, depth: nextDepth } = stack[i + 1];
    if(depth == nextDepth) {
      node.next = nextNode;
    } else {
      node.next = null;
    }
  }
  return root;
};
let root = [1,2,3,4,5,null,7];
console.log(connect(createTree(root)));



